#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing.h>
#include <dlib/dnn.h>
#include <dlib/image_io.h>
#include <iostream>
#include <resnet.h>

using namespace dlib;
using namespace std;

anet_type net;

double cosine_similarity(const matrix<float,0,1>& A, const matrix<float,0,1>& B) {
    double dot_product = dot(A, B);
    double norm_a = length(A);
    double norm_b = length(B);
    return dot_product / (norm_a * norm_b);
}

int main(int argc, char** argv) {
    if (argc != 3) {
        cout << "用法: ./face_cmp <practice/dlib/myapp/build/2.jpg> <practice/dlib/myapp/build/3.jpg>" << endl;
        return -1;
    }

    frontal_face_detector detector = get_frontal_face_detector();
    shape_predictor sp;
    deserialize("/home/hhy212306170/practice/model/shape_predictor_5_face_landmarks.dat") >> sp;
    deserialize("/home/hhy212306170/practice/model/dlib_face_recognition_resnet_model_v1.dat") >> net;

    matrix<rgb_pixel> img1;
    load_image(img1, argv[1]);
    matrix<rgb_pixel> img2;
    load_image(img2, argv[2]);

    std::vector<rectangle> faces1 = detector(img1);
    if (faces1.empty()) {
        cout << "第一张图片未检测到人脸" << endl;
        return -1;
    }

    std::vector<rectangle> faces2 = detector(img2);
    if (faces2.empty()) {
        cout << "第二张图片未检测到人脸" << endl;
        return -1;
    }

    auto shape1 = sp(img1, faces1[0]);
    matrix<rgb_pixel> face_chip1;
    extract_image_chip(img1, get_face_chip_details(shape1, 150, 0.25), face_chip1);

    auto shape2 = sp(img2, faces2[0]);
    matrix<rgb_pixel> face_chip2;
    extract_image_chip(img2, get_face_chip_details(shape2, 150, 0.25), face_chip2);

    matrix<float,0,1> face_descriptor1 = net(face_chip1);
    matrix<float,0,1> face_descriptor2 = net(face_chip2);

    double cos_sim = cosine_similarity(face_descriptor1, face_descriptor2);
    double distance = length(face_descriptor1 - face_descriptor2);

    cout << "欧氏距离: " << distance << endl;
    cout << "余弦相似度: " << cos_sim << endl;

    if (distance < 0.6 && cos_sim > 0.8) {
        cout << "人脸相似度高，很可能是同一个人" << endl;
    } else {
        cout << "人脸相似度低，可能是不同人" << endl;
    }

    return 0;
}